package com.rongma.waterdrop.utils;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 * Java大数运算
 * Created by RongMa on 16/5/31.
 */
public class Arith
{

    /**
     * 加法
     * @param value1
     * @param value2
     * @return
     */
    public static double add(double value1,double value2){
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 减法
     * @param value1
     * @param value2
     * @return
     */
    public static double sub(double value1,double value2){
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 乘法
     * @param value1
     * @param value2
     * @return
     */
    public static double mul(double value1,double value2){
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 除法
     * @param value1 除数
     * @param value2 被除数
     * @param scale 精确度
     * @return 运算结果
     * @throws IllegalAccessException
     */
    public static double div(double value1,double value2,int scale) throws IllegalAccessException{
        //如果精确范围小于0，抛出异常信息
        if(scale<0){
            throw new IllegalAccessException("精确度不能小于0");
        }
        if(value2 == 0)
        {
            throw new IllegalAccessException("被除数不能为0");
        }
        MathContext mc = new MathContext(scale, RoundingMode.DOWN);
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.divide(b2, mc).doubleValue();
    }

    /**
     * 取余
     * @param value1 除数
     * @param value2 被除数
     * @return 余数
     * @throws IllegalAccessException
     */
    public static int divAndRemainder(double value1,double value2) throws IllegalAccessException{
        if(value2 == 0)
        {
            throw new IllegalAccessException("被除数不能为0");
        }
        MathContext mc = new MathContext(0, RoundingMode.DOWN);
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.divideAndRemainder(b2,mc)[1].intValue();
    }






}
